package com.yzf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzf.common.BaseContext;
import com.yzf.common.R;
import com.yzf.dto.OrdersDto;
import com.yzf.entity.AddressBook;
import com.yzf.entity.OrderDetail;
import com.yzf.entity.Orders;
import com.yzf.entity.ShoppingCart;
import com.yzf.service.AddressBookService;
import com.yzf.service.OrderDetailService;
import com.yzf.service.OrdersService;
import com.yzf.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yzf
 * @description
 * @since 2023/2/28 21:13
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;


    @PostMapping("submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info(orders.toString());
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String number){
        Page<Orders> ordersPage = new Page(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number!=null,Orders::getNumber,number);
        ordersService.page(ordersPage,queryWrapper);
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<OrdersDto> records = ordersPage.getRecords().stream().map((item)->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            ordersDto.setUserName(item.getConsignee());
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> list = orderDetailService.list(wrapper);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(records);
        return R.success(ordersDtoPage);
    }

}
